package com.yiren.dbaa.module.project_edit.view.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.enums.DetourCheckTypeEnum;
import com.yiren.backstage.config.enums.SczbEndConditionEnum;
import com.yiren.backstage.config.enums.SiteConfigCodeEnum;
import com.yiren.backstage.currency.bean.SczbStartVoiceBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.db.dao.bean.SynExamBean;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.currency.fragment.LazyLoadFragment;
import com.yiren.dbaa.currency.model.CheckBoxCommonModel;
import com.yiren.dbaa.currency.model.EdittextCommonModel;
import com.yiren.dbaa.module.project_edit.service.ICreateView;
import com.yiren.dbaa.module.project_edit.service.impl.CreateViewImpl;
import com.yiren.dbaa.module.project_edit.view.adapter.SelectParamAdapter;
import com.yiren.dbaa.util.DensityUtil;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/11/4 9:13
 * @description: 上车准备fragment
 */
public class SczbFragment extends LazyLoadFragment {

    @BindView(R.id.cb_close_engine)
    CheckBox cbCloseEngine;
    @BindView(R.id.et_close_engine)
    EditText etCloseEngine;
    @BindView(R.id.et_close_engine_time)
    EditText etCloseEngineTime;
    @BindView(R.id.ll_voice_values)
    LinearLayout llVoiceValues;
    @BindView(R.id.tv_detour_check)
    TextView tvDetourCheck;
    @BindView(R.id.tv_end_condition)
    TextView tvEndCondition;
    @BindView(R.id.et_delay_time)
    EditText etDelayTime;
    @BindView(R.id.et_left_head_voice)
    EditText etLeftHeadVoice;
    @BindView(R.id.et_right_head_voice)
    EditText etRightHeadVoice;
    @BindView(R.id.et_left_tail_voice)
    EditText etLeftTailVoice;
    @BindView(R.id.et_right_tail_voice)
    EditText etRightTailVoice;
    @BindView(R.id.cb_judge_adjust)
    CheckBox cbJudgeAdjust;
    @BindView(R.id.et_seat_voice)
    EditText etSeatVoice;
    @BindView(R.id.et_rearview_voice)
    EditText etRearviewVoice;
    @BindView(R.id.et_reflector_voice)
    EditText etReflectorVoice;

    /*** 动态声音提示编辑框 */
    private List<EditText> editVoiceList;
    /*** 动态时间间隔编辑框 */
    private List<EditText> editTimeList;
    /*** 上车准备初始语音集合 */
    private List<SczbStartVoiceBean> sczbStartVoices;
    /*** 动态开始播报语音集合 */
    private List<LinearLayout> llIdentifyVoices;
    /*** 创建控件 */
    private ICreateView iCreateView;

    /*** 绕车方式 */
    private DetourCheckTypeEnum detourCheckType;
    /*** 结束条件 */
    private SczbEndConditionEnum endCondition;

    /**
     * 设置对话框的值  1:绕车类型  2：上车准结束条件 3：选择单位类型
     */
    private List<String> selectList;
    private String selectString;

    private SiteEntity site;
    /*** 存放参数值改变的临时map */
    private Map<String, Object> tempMap;
    private boolean isPartner;
    private SynExamBean synExamBean;
    private Gson gs = new Gson();
    private List<EdittextCommonModel> edittextCommonModels;
    private List<CheckBoxCommonModel> checkBoxCommonModels;

    @Override
    protected int setContentView() {
        return R.layout.fragment_sczb;
    }

    @Override
    protected void init() {
        initData();
        setData();
        addIdentifyVoiceList();
        setEditText();
        setCheckBox();
    }

    private void initData() {
        site = (SiteEntity) getArguments().getSerializable("site");
        isPartner = LoadConfigApi.loadUserParamConfig(getActivity()).isPartner();
        tempMap = new HashMap<>();
        synExamBean = gs.fromJson(isPartner ? site.getPartneModifyVal() : site.getCoachModifyVal(), new TypeToken<SynExamBean>() {
        }.getType());
        if (null == synExamBean) synExamBean = new SynExamBean();
        selectList = new ArrayList<String>();
        iCreateView = new CreateViewImpl();
        llVoiceValues.removeAllViews();
        editTimeList = new ArrayList<>();
        editVoiceList = new ArrayList<>();
        llIdentifyVoices = new ArrayList<>();
    }

    private void setData() {
        //绕车感应要求
        detourCheckType = DetourCheckTypeEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S5.toString()));
        tvDetourCheck.setText(detourCheckType.getDescription());
        //上车准备结束条件
        endCondition = SczbEndConditionEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S6.toString()));
        tvEndCondition.setText(endCondition.getDescription());
    }

    private void addIdentifyVoiceList() {
        sczbStartVoices = gs.fromJson((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.S4.toString()), new TypeToken<List<SczbStartVoiceBean>>() {
        }.getType());
        for (int i = 0; i < sczbStartVoices.size(); i++) {
            LinearLayout linearLayout = iCreateView.addChildLinearLayout(getActivity());
            TextView tv1;
            if (i == 0) {
                tv1 = iCreateView.addVoiceValueTextView(getActivity(), 0);
                tv1.setText("开始播报");
            } else {
                tv1 = iCreateView.addVoiceValueTextView(getActivity(), 0);
                tv1.setText("                  ");
            }
            EditText et1 = iCreateView.addVoiceValueEditText(getActivity());
            et1.setText(sczbStartVoices.get(i).getContent());
            editVoiceList.add(et1);
            TextView tv2 = iCreateView.addVoiceValueTextView(getActivity(), 1);
            tv2.setText("等待");
            EditText et2 = iCreateView.addEditText(getActivity());
            et2.setText(sczbStartVoices.get(i).getKeepTime() + "");
            editTimeList.add(et2);
            TextView tv3 = iCreateView.addVoiceValueTextView(getActivity(), 1);
            tv3.setText("秒后提示");
            linearLayout.addView(tv1);
            linearLayout.addView(et1);
            linearLayout.addView(tv2);
            linearLayout.addView(et2);
            linearLayout.addView(tv3);
            llIdentifyVoices.add(linearLayout);
            llVoiceValues.addView(linearLayout);
        }
    }

    private void setEditText() {
        edittextCommonModels = new ArrayList<>();
        edittextCommonModels.add(new EdittextCommonModel(etCloseEngine, SiteConfigCodeEnum.S2.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etCloseEngineTime, SiteConfigCodeEnum.S3.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etDelayTime, SiteConfigCodeEnum.S7.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etLeftHeadVoice, SiteConfigCodeEnum.S8.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etRightHeadVoice, SiteConfigCodeEnum.S9.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etLeftTailVoice, SiteConfigCodeEnum.S10.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etRightTailVoice, SiteConfigCodeEnum.S11.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etSeatVoice, SiteConfigCodeEnum.S13.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etRearviewVoice, SiteConfigCodeEnum.S14.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etReflectorVoice, SiteConfigCodeEnum.S15.toString()));
        for (EdittextCommonModel model : edittextCommonModels) {
            model.getEt().setText(model.getInitValue());
            model.getEt().addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    SignalGConstant.examConfigMap.put(model.getKey(), s.toString());
                    if (!s.toString().equals(model.getInitValue())) {
                        tempMap.put(model.getKey(), s.toString());
                    } else {
                        tempMap.remove(model.getKey());
                    }
                }
            });
        }
    }

    private void setCheckBox() {
        checkBoxCommonModels = new ArrayList<>();
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbCloseEngine, SiteConfigCodeEnum.S1.toString()));
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbJudgeAdjust, SiteConfigCodeEnum.S12.toString()));
        for (CheckBoxCommonModel model : checkBoxCommonModels) {
            model.getCb().setChecked(model.isInitValue());
            model.getCb().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    SignalGConstant.examConfigMap.put(model.getKey(), isChecked);
                    if (isChecked != model.isInitValue()) {
                        tempMap.put(model.getKey(), isChecked);
                    } else {
                        tempMap.remove(model.getKey());
                    }
                }
            });
        }
    }

    @OnClick({R.id.tv_detour_check, R.id.tv_end_condition, R.id.tv_add_value, R.id.tv_delete_value, R.id.tv_save_param})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_detour_check:
                setDialogValues(1, "请选择绕车检测方式 ", tvDetourCheck);
                break;
            case R.id.tv_end_condition:
                setDialogValues(2, "请选择上车准备结束条件 ", tvEndCondition);
                break;
            case R.id.tv_add_value:
                LinearLayout linearLayout = iCreateView.addChildLinearLayout(getActivity());
                TextView tv1 = iCreateView.addVoiceValueTextView(getActivity(), 0);
                tv1.setText("                  ");
                EditText et1 = iCreateView.addVoiceValueEditText(getActivity());
                editVoiceList.add(et1);
                TextView tv2 = iCreateView.addVoiceValueTextView(getActivity(), 1);
                tv2.setText("等待");
                EditText et2 = iCreateView.addEditText(getActivity());
                editTimeList.add(et2);
                TextView tv3 = iCreateView.addVoiceValueTextView(getActivity(), 1);
                tv3.setText("秒后提示");
                linearLayout.addView(tv1);
                linearLayout.addView(et1);
                linearLayout.addView(tv2);
                linearLayout.addView(et2);
                linearLayout.addView(tv3);
                llIdentifyVoices.add(linearLayout);
                llVoiceValues.addView(linearLayout);
                break;
            case R.id.tv_delete_value:
                if (llIdentifyVoices.size() > 2) {
                    llVoiceValues.removeView(llIdentifyVoices.get(llIdentifyVoices.size() - 1));
                    editVoiceList.remove(llIdentifyVoices.size() - 1);
                    editTimeList.remove(llIdentifyVoices.size() - 1);
                    llIdentifyVoices.remove(llIdentifyVoices.size() - 1);
                }
                break;
            case R.id.tv_save_param:
                boolean isChange = false;  //动态语音是否改变
                if (editVoiceList.size() == sczbStartVoices.size()) {
                    for (int i = 0; i < sczbStartVoices.size(); i++) {
                        if (editVoiceList.get(i).getText().toString().equals(sczbStartVoices.get(i).getContent()) && Integer.parseInt(editTimeList.get(i).getText().toString()) == sczbStartVoices.get(i).getKeepTime()) {
                            continue;
                        } else {
                            isChange = true;
                        }
                    }
                } else {
                    isChange = true;
                }
                if (isChange) {
                    List<SczbStartVoiceBean> sczbStartVoices = new ArrayList<>();
                    for (int i = 0; i < editVoiceList.size(); i++) {
                        sczbStartVoices.add(new SczbStartVoiceBean(editVoiceList.get(i).getText().toString(), Integer.parseInt(editTimeList.get(i).getText().toString())));
                    }
                    String json = gs.toJson(sczbStartVoices);
                    tempMap.put(SiteConfigCodeEnum.S4.toString(), json);
                    SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.S4.toString(), json);
                }
                if (tempMap.size() == 0) return;
                for (String key : tempMap.keySet()) {
                    synExamBean.getExamConfigMap().put(key, tempMap.get(key));
                }
                if (isPartner) {
                    site.setPartneModifyVal(gs.toJson(synExamBean));
                } else {
                    site.setCoachModifyVal(gs.toJson(synExamBean));
                }
                UserDbController.getInstance(false).update(site);
                MessageBox.show(getActivity(), "保存成功!");
                break;
        }
    }

    private void setDialogValues(int type, String title, TextView tv) {
        selectList.clear();
        selectString = tv.getText().toString();
        switch (type) {
            case 1:
                DetourCheckTypeEnum[] detourCheckTypes = DetourCheckTypeEnum.values();
                for (int i = 0; i < detourCheckTypes.length; i++) {
                    selectList.add(detourCheckTypes[i].getDescription());
                }
                break;
            case 2:
                SczbEndConditionEnum[] sczbEndConditions = SczbEndConditionEnum.values();
                for (int i = 0; i < sczbEndConditions.length; i++) {
                    selectList.add(sczbEndConditions[i].getDescription());
                }
                break;
        }
        showSelectDialog(type, title, tv);
    }

    /**
     * 弹出框选择（type 1:绕车 2：上车准备结束 ）
     */
    public void showSelectDialog(int type, String title, TextView tv) {
        Dialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (DensityUtil.getScreenWidth(getActivity()) * 7) / 10;
        params.height = (DensityUtil.getScreenHeight(getActivity()) * 6) / 10;
        dialog.getWindow().setAttributes(params);
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_select_box);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        ListView lvList = (ListView) window.findViewById(R.id.lv_dialog_list);
        lvList.setDivider(null);// 去除listview的下划线
        tvTitle.setText(title);
        SelectParamAdapter adapter = new SelectParamAdapter(getActivity(), selectList, selectString);
        lvList.setAdapter(adapter);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv.setText(selectList.get(position));
                switch (type) {
                    case 1:  //绕车检测类型
                        DetourCheckTypeEnum[] detourCheckTypes = DetourCheckTypeEnum.values();
                        if (!detourCheckType.equals(detourCheckTypes[position])) {
                            SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.S5.toString(), detourCheckTypes[position].toString());
                            tempMap.put(SiteConfigCodeEnum.S5.toString(), detourCheckTypes[position].toString());
                        } else {
                            tempMap.remove(SiteConfigCodeEnum.S5.toString());
                        }
                        break;
                    case 2:  //上车准备结束类型
                        SczbEndConditionEnum[] sczbEndConditions = SczbEndConditionEnum.values();
                        if (!endCondition.equals(sczbEndConditions[position])) {
                            SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.S6.toString(), sczbEndConditions[position].toString());
                            tempMap.put(SiteConfigCodeEnum.S6.toString(), sczbEndConditions[position].toString());
                        } else {
                            tempMap.remove(SiteConfigCodeEnum.S6.toString());
                        }
                        break;
                }
                dialog.dismiss();
            }
        });
    }

}
